<template>
  <!-- destroy-on-close: 关闭之后销毁组件 -->
  <el-drawer
    title="设置轮播图"
    v-model="dialogVisible"
    size="50%"
    :destroy-on-close="true"
    :show-close="true"
    :wrapperClosable="true"
  >
    <el-form :model="form" label-width="80px">
      <el-form-item label="轮播图">
        <choose-image v-model="form.banners" :limit="9" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="sumbit" :loading="loading">
          提交
        </el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script setup>
  import { ref, reactive } from 'vue'
  import { readGoodsApi, setGoodsBannerApi } from '@/api/goods'
  import ChooseImage from '@/components/ChooseImage.vue'
  import { toast } from '@/utils'

  const emit = defineEmits(['reloadData'])
  const dialogVisible = ref(false)
  const form = reactive({
    banners: [],
  })

  const goodsId = ref(0)
  function open(row) {
    goodsId.value = row.id
    row.bannersLoading = true
    readGoodsApi(goodsId.value)
      .then((res) => {
        form.banners = res.goodsBanner.map((o) => o.url)
        dialogVisible.value = true
      })
      .finally(() => (row.bannersLoading = false))
  }

  const loading = ref(false)
  function sumbit() {
    loading.value = true
    setGoodsBannerApi(goodsId.value, form)
      .then((res) => {
        toast('设置轮播图成功')
        dialogVisible.value = false
        emit('reloadData')
      })
      .finally(() => (loading.value = false))
  }

  defineExpose({
    open,
  })
</script>

<style scoped></style>
